<template>
    <div class="container">
      <h1>Incident Overview</h1>
      
      <!-- 搜索框 -->
      <div class="search-container">
        <input v-model="searchTerm" @input="fetchIncidents" placeholder="搜索 Inc_id" />
        <input v-model="currentUserNickname" placeholder="搜索 Opened By" disabled />
        <input v-model="searchPriority" @input="fetchIncidents" placeholder="搜索 Priority" />
        <input v-model="searchProject" @input="fetchIncidents" placeholder="搜索 Project" />
        <input v-model="searchShortDescription" @input="fetchIncidents" placeholder="搜索 Short Description" />
        <input v-model="searchAssignedTo" @input="fetchIncidents" placeholder="搜索 Assigned To" />
        <input v-model="searchAssignmentGroup" @input="fetchIncidents" placeholder="搜索 Assig Group" />
        <input v-model="searchIncidentState" @input="fetchIncidents" placeholder="搜索 Incident State" />
        <button @click="showConfirmationDialog" :disabled="selectedIncidents.length === 0">删除</button>
      </div>
      
      <!-- 表格 -->
      <table>
        <thead>
          <tr>
            <th>Select</th> <!-- 新增复选框列 -->
            <th>Inc_id</th>
            <th>Opened</th>
            <th>Resolved</th>
            <th>Opened By</th>
            <th>Priority</th>
            <th>Project</th>
            <th>Short Description</th>
            <th>Description</th>
            <th>Assigned To</th>
            <th>Assignment Group</th>
            <th>Incident State</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="incident in incidents" :key="incident.id">
            <td>
              <input type="checkbox" :value="incident.Inc_id" v-model="selectedIncidents" />
            </td>
            <td @click="goToDetail(incident.Inc_id)" class="clickable">{{ incident.Inc_id }}</td>
            <td>{{ formatDate(incident.Opened) }}</td>
            <td>{{ formatDate(incident.Resolved) }}</td>
            <td>{{ incident.Opened_by }}</td>
            <td>{{ incident.Priority }}</td>
            <td>{{ incident.Project }}</td>
            <td>
              <span @click="toggleFullDescription(incident.id, 'short')">
                {{ incident.Short_description.substring(0, 15) }}<span v-if="fullDescriptionId === incident.id && fullDescriptionType === 'short'">...{{ incident.Short_description }}</span>
              </span>
            </td>
            <td>
              <span @click="toggleFullDescription(incident.id, 'description')">
                {{ incident.Description.substring(0, 15) }}<span v-if="fullDescriptionId === incident.id && fullDescriptionType === 'description'">...{{ incident.Description }}</span>
              </span>
            </td>
            <td>{{ incident.Assigned_to }}</td>
            <td>{{ incident.Assignment_group }}</td>
            <td>{{ incident.Incident_state }}</td>
          </tr>
        </tbody>
      </table>
      
      <!-- 分页 -->
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span>第 {{ currentPage }} 页，共 {{ total }} 条</span>
        <button @click="nextPage" :disabled="currentPage * limit >= total">下一页</button>
      </div>
      
      <!-- 删除确认对话框 -->
      <ConfirmationDialog 
        v-if="isConfirmationDialogVisible" 
        @confirm="deleteSelectedIncidents" 
        @cancel="hideConfirmationDialog" 
      />
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import ConfirmationDialog from '../components/ConfirmationDialog.vue'; // 引入确认对话框组件
  
  export default {
    components: {
      ConfirmationDialog
    },
    setup() {
      const incidents = ref([]);
      const total = ref(0);
      const currentPage = ref(1);
      const limit = ref(10);
      const searchTerm = ref('');
      const currentUserNickname = ref('');
      const searchPriority = ref('');
      const searchProject = ref('');
      const searchShortDescription = ref('');
      const searchAssignedTo = ref('');
      const searchAssignmentGroup = ref('');
      const searchIncidentState = ref('');
      const selectedIncidents = ref([]); // 用于存储选中的 Incident ID
      const router = useRouter();
      const fullDescriptionId = ref(null);
      const fullDescriptionType = ref(null);
      const isConfirmationDialogVisible = ref(false); // 控制确认对话框的显示
  
      // 显示确认对话框
      const showConfirmationDialog = () => {
        if (selectedIncidents.value.length === 0) {
          alert("请选择要删除的项");
        } else {
          isConfirmationDialogVisible.value = true;
        }
      };
  
      // 隐藏确认对话框
      const hideConfirmationDialog = () => {
        isConfirmationDialogVisible.value = false;
      };
  
      // 删除选中的 Incident
      const deleteSelectedIncidents = async () => {
        try {
          await axios.delete('http://localhost:3000/api/incidents', {
            data: { incIds: selectedIncidents.value }
          });
          incidents.value = incidents.value.filter(incident => !selectedIncidents.value.includes(incident.Inc_id));
          selectedIncidents.value = [];
          alert("Incident删除成功");
          hideConfirmationDialog();
        } catch (error) {
          console.error("删除失败:", error);
          alert("删除失败：" + error.message);
        }
      };
  
      // 获取当前用户的昵称
      onMounted(async () => {
        const username = localStorage.getItem('username');
        const userRole = localStorage.getItem('userRole');
        if (username && userRole) {
          try {
            const response = await axios.post('http://localhost:3000/api/getNickname', { username, userRole });
            currentUserNickname.value = response.data.nickname;
            if (currentUserNickname.value) {
              fetchIncidents();
            }
          } catch (error) {
            console.error('获取用户昵称失败:', error);
          }
        }
      });
  
      const fetchIncidents = async () => {
        try {
          const response = await axios.get('http://localhost:3000/api/incidents', {
            params: {
              page: currentPage.value,
              limit: limit.value,
              search: searchTerm.value || 
                      searchPriority.value || 
                      searchProject.value || 
                      searchShortDescription.value ||
                      searchAssignedTo.value ||
                      searchAssignmentGroup.value ||
                      searchIncidentState.value,
              openedBy: currentUserNickname.value
            }
          });
          incidents.value = response.data.incidents;
          total.value = response.data.total;
        } catch (error) {
          console.error('获取数据失败:', error);
        }
      };
  
      const nextPage = () => {
        if (currentPage.value * limit.value < total.value) {
          currentPage.value++;
          fetchIncidents();
        }
      };
  
      const prevPage = () => {
        if (currentPage.value > 1) {
          currentPage.value--;
          fetchIncidents();
        }
      };
  
      const goToDetail = (incId) => {
        router.push({ name: 'IncidentDetailforObyMe', params: { incId } });
      };
  
      const formatDate = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleString();
      };
  
      const toggleFullDescription = (id, type) => {
        if (fullDescriptionId.value === id && fullDescriptionType.value === type) {
          fullDescriptionId.value = null;
          fullDescriptionType.value = null;
        } else {
          fullDescriptionId.value = id;
          fullDescriptionType.value = type;
        }
      };
  
      return {
        incidents,
        total,
        currentPage,
        limit,
        searchTerm,
        currentUserNickname,
        searchPriority,
        searchProject,
        searchShortDescription,
        searchAssignedTo,
        searchAssignmentGroup,
        searchIncidentState,
        selectedIncidents,
        fetchIncidents,
        deleteSelectedIncidents,
        nextPage,
        prevPage,
        goToDetail,
        formatDate,
        toggleFullDescription,
        fullDescriptionId,
        fullDescriptionType,
        isConfirmationDialogVisible,
        showConfirmationDialog,
        hideConfirmationDialog
      };
    }
  };
  </script>
   <style scoped>
   .container {
     max-width: 1500px;
     padding: 10px;
     margin-bottom: 150px;
     background-color: white; /* 白色背景 */
     border-radius: 10px; /* 圆角 */
     padding: 20px; /* 内边距 */
     box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
   }
   
   h1 {
     margin-top: 10px;
     margin-bottom: 10px;
   }
   
   .search-container {
     margin-bottom: 20px;
   }
   
   .search-container input {
     margin-right: 10px;
     width: 120px;
     border-radius: 4px; /* 圆角 */
     border: 1px solid #ccc; /* 边框颜色 */
     padding: 8px; /* 内边距 */
     transition: border-color 0.3s; /* 边框颜色过渡效果 */
   }
   
   .search-container input:hover {
     border-color: #007bff; /* 悬停时边框颜色 */
   }
   
   .search-container button {
     background-color: red; /* 蓝色背景 */
     color: white; /* 白色文字 */
     border: none;
     border-radius: 4px; /* 圆角 */
     padding: 8px 16px; /* 内边距 */
     margin-left: 10px; /* 与搜索框的间距 */
     cursor: pointer;
     transition: background-color 0.3s; /* 颜色过渡效果 */
   }
   
   .search-container button:hover {
     background-color: #410303; /* 悬停时深红色背景 */
   }
   
   .search-container button:disabled {
     background-color: #ccc; /* 禁用状态的灰色背景 */
     cursor: not-allowed;
   }
   
   table {
     width: 100%;
     border-collapse: collapse;
     font-size: 13px;
   }
   
   table th, table td {
     border: 1px solid #ddd;
     padding: 4px;
   }
   
   .clickable {
     color: blue;
     cursor: pointer;
   }
   
   .pagination {
     margin-top: 20px;
     display: flex;
     justify-content: center; /* 水平居中 */
     align-items: center; /* 垂直居中 */
   }
   
   .pagination button {
     background-color: #007bff; /* 蓝色背景 */
     color: white; /* 白色文字 */
     border: none;
     border-radius: 4px; /* 圆角 */
     padding: 8px 16px; /* 内边距 */
     margin: 0 10px; /* 按钮间距 */
     cursor: pointer;
     transition: background-color 0.3s; /* 颜色过渡效果 */
   }
   
   .pagination button:hover {
     background-color: #0056b3; /* 悬停时深蓝色背景 */
   }
   
   .pagination button:disabled {
     background-color: #ccc; /* 禁用状态的灰色背景 */
     cursor: not-allowed;
   }
   </style>